package com.example.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.lib_base.BaseViewModel
import com.example.module_home.intent.HomeIntent
import com.example.module_home.model.HomeModel
import com.example.module_home.state.HomeState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class HomeViewModel:BaseViewModel<HomeIntent>() {
   private val model by lazy{HomeModel()}
    private val mutableState= MutableStateFlow<HomeState>(HomeState.Loading)
    val observerState:StateFlow<HomeState>
    get() = mutableState
    init {
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                when(it){
                    is HomeIntent.GetRVideo->{
                        val recommendVideo = model.getRecommendVideo(it.page, it.size)
                        if(recommendVideo.code==0){
                            mutableState.value=HomeState.RVideoSuccess(recommendVideo.data)
                        }else{
                            mutableState.value=HomeState.Failure(recommendVideo.msg)
                        }
                    }
                    is HomeIntent.GetComment->{
                        val comment = model.getComment(it.type, it.id)
                        if(comment.code==0){
                            mutableState.value=HomeState.CommentSuccess(comment.data)
                        }else{
                            mutableState.value=HomeState.Failure(comment.msg)
                        }
                    }
                }
            }
        }
    }
}